<!--
 * @Author: ZAL 2177624751@qq.com
 * @Date: 2025-02-11 14:44:27
 * @LastEditors: ZAL 2177624751@qq.com
 * @LastEditTime: 2025-03-31 21:12:53
 * @FilePath: \moldlifecycle-webc:\Users\21776\Desktop\毕设\shop_app_vue3\pages\order\order.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <view class="container">
    <!-- 顶部标签页 -->
    <scroll-view 
      class="tabs-container" 
      scroll-x 
      :show-scrollbar="false"
      :enhanced="true"
      :paging-enabled="false"
    >
      <view class="tabs">
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'all' }"
          @click="switchTab('all')"
        >
          全部
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'unpaid' }"
          @click="switchTab('unpaid')"
        >
          待付款
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'unshipped' }"
          @click="switchTab('unshipped')"
        >
          待发货
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'unreceived' }"
          @click="switchTab('unreceived')"
        >
          待收货
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'received' }"
          @click="switchTab('received')"
        >
          已收货
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'canceled' }"
          @click="switchTab('canceled')"
        >
          已取消
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'unrated' }"
          @click="switchTab('unrated')"
        >
          待评价
        </view>
        <view 
          class="tab-item" 
          :class="{ active: activeTab === 'rated' }"
          @click="switchTab('rated')"
        >
          已评价
        </view>
      </view>
    </scroll-view>

    <!-- 订单列表 -->
    <scroll-view 
      class="order-list" 
      scroll-y 
      v-if="orderList.length > 0"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <view 
        class="order-item" 
        v-for="order in orderList" 
        :key="order.id"
        @click="navigateToOrderDetail(order)"
        hover-class="item-hover"
      >
        <!-- 订单头部 -->
        <view class="order-header">
          <text class="order-no">订单号：{{ order.orderNo }}</text>
          <text class="order-status" :class="getStatusClass(order.status)">{{ order.statusDesc }}</text>
        </view>

        <!-- 商品信息 -->
        <view 
          class="product-item" 
          v-for="item in order.orderItems" 
          :key="item.id"
        >
          <image :src="item.fruitImage" mode="aspectFill" class="product-image" />
          <view class="product-info">
            <text class="product-name">{{ item.fruitName }}</text>
            <view class="product-price-wrap">
              <text class="product-price">￥{{ item.price }}</text>
              <text class="product-quantity">x{{ item.quantity }}</text>
            </view>
          </view>
        </view>

        <!-- 订单底部 -->
        <view class="order-footer">
          <view class="total-wrap">
            <text>共{{ getTotalQuantity(order) }}件商品</text>
            <text class="total-price">实付：￥{{ order.payAmount }}</text>
          </view>
          
          <!-- 操作按钮 -->
          <view class="action-buttons" @click.stop>
            <template v-if="order.status === 0">
              <button 
                class="btn-primary" 
                @click="payOrder(order)"
              >
                立即支付
              </button>
              <button 
                class="btn-secondary" 
                @click="cancelOrder(order)"
              >
                取消订单
              </button>
            </template>
            
            <template v-else-if="order.status === 1">
              <button class="btn-secondary">
                提醒发货
              </button>
            </template>
            
            <template v-else-if="order.status === 2">
              <button 
                class="btn-primary"
                @click="confirmReceive(order)"
              >
                确认收货
              </button>
              <button 
                class="btn-secondary"
                @click="checkLogistics(order)"
              >
                查看物流
              </button>
            </template>
            
            <template v-else-if="order.status === 3">
              <button 
                class="btn-primary" 
                v-if="!isRated(order)"
                @click="showRateDialog(order)"
              >
                评价
              </button>
              <button 
                class="btn-secondary"
                @click="navigateToApplyAftersale(order)"
              >
                申请售后
              </button>
            </template>

            <template v-else-if="order.status === 5">
              <button 
                class="btn-primary" 
                @click="showRateDialog(order)"
              >
                去评价
              </button>
            </template>

            <template v-else-if="order.status === 6">
              <button 
                class="btn-secondary" 
                @click="viewRate(order)"
              >
                查看评价
              </button>
            </template>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 空状态 -->
    <view v-else class="empty-state">
      <image src="/static/images/empty_order.png" mode="aspectFit" class="empty-image" />
      <text>暂无相关订单</text>
      <button class="btn-aftersale" @click="navigateToAftersale">查看售后</button>
    </view>

    <!-- 加载提示 -->
    <!-- <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text>加载中...</text>
    </view> -->

    <!-- 评价弹窗 -->
    <up-popup :show="showRating" mode="bottom" :safe-area-inset-bottom="true" :round="10" :closeable="true" @close="showRating = false">
      <view class="rating-dialog">
        <view class="rating-header">
          <text class="title">商品评价</text>
          <up-icon name="close" @click="showRating = false" />
        </view>
        
        <view class="rating-content">
          <view class="rate-product" v-if="currentOrderItem">
            <image :src="currentOrderItem.fruitImage" mode="aspectFill" class="product-image" />
            <text class="product-name">{{ currentOrderItem.fruitName }}</text>
          </view>
          
          <view class="rate-item">
            <text>商品评分</text>
            <up-rate v-model="ratingForm.score" count="5" />
          </view>
          
          <view class="rate-item">
            <text>评价内容</text>
            <textarea 
              v-model="ratingForm.content"
              placeholder="请输入您的评价内容"
              class="rate-textarea"
            />
          </view>
          
          <view class="rate-item">
            <text>上传图片</text>
            <up-upload
              :file-list="ratingForm.images"
              @afterRead="afterRead"
              @delete="deletePic"
              name="1"
              multiple
              :max-count="4"
            />
          </view>
        </view>
        
        <view class="rating-footer">
          <button 
            class="btn-submit" 
            @click="submitRating"
            :disabled="submitting"
          >
            {{ submitting ? '提交中...' : '提交评价' }}
          </button>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue'
import { onLoad} from '@dcloudio/uni-app'
import { useOrderStore } from '../../store/orderStore.js'
import { useReviewStore } from '../../store/reviewStore.js'

// 创建store
const orderStore = useOrderStore()
const reviewStore = useReviewStore()

// 数据状态
const activeTab = ref('unrated')
const refreshing = ref(false)
const loading = ref(false)
const showRating = ref(false)
const currentOrder = ref(null)
const currentOrderItem = ref(null)
const submitting = ref(false)
const ratingForm = ref({
  score: 5,
  content: '',
  images: []
})

// 计算属性
const orderList = computed(() => orderStore.getOrderList || [])

// 页面加载
onLoad((options) => {
  if (options.status) {
    const status = parseInt(options.status)
    switch (status) {
      case 0:
        activeTab.value = 'unpaid'
        break
      case 1:
        activeTab.value = 'unshipped'
        break
      case 2:
        activeTab.value = 'unreceived'
        break
      case 3:
        activeTab.value = 'received'
        break
      case 4:
        activeTab.value = 'canceled'
        break
      case 5:
        activeTab.value = 'unrated'
        break
      case 6:
        activeTab.value = 'rated'
        break
      default:
        activeTab.value = 'all'
    }
    loadOrders(status)
  } else {
    activeTab.value = 'all'
    loadOrders()
  }
})

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true
  await loadOrders()
  refreshing.value = false
}

// 切换标签
const switchTab = (tab) => {
  activeTab.value = tab
  let status
  switch (tab) {
    case 'all':
      status = ''
      break
    case 'unpaid':
      status = 0
      break
    case 'unshipped':
      status = 1
      break
    case 'unreceived':  
      status = 2
      break
    case 'received':
      status = 3
      break
    case 'canceled':
      status = 4
      break
    case 'unrated':
      status = 5
      break
    case 'rated':
      status = 6
      break
    default:
      status = ''
  }
  loadOrders(status)
}

// 获取订单列表
const loadOrders = async (status = '') => {
  try {
    loading.value = true
    await orderStore.loadOrderList({ status })
  } catch (error) {
    console.error('获取订单列表失败', error)
    uni.showToast({
      title: '获取订单列表失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
    uni.stopPullDownRefresh()
  }
}

// 显示评价弹窗
const showRateDialog = (order) => {
  console.log('showRateDialog order:', order)
  console.log('showRateDialog orderItems:', order.orderItems)
  
  currentOrder.value = order
  currentOrderItem.value = order.orderItems[0]
  
  console.log('currentOrderItem after set:', currentOrderItem.value)
  
  ratingForm.value = {
    score: 5,
    content: '',
    images: []
  }
  showRating.value = true
}

// 判断订单是否已评价
const isRated = (order) => {
  return order.orderItems.some(item => item.isRated)
}

// 查看评价
const viewRate = async (order) => {
  try {
    await reviewStore.loadReviewList(currentOrderItem.value.fruitId)
    const reviews = reviewStore.getReviews
    
    if (reviews && reviews.length > 0) {
      uni.showToast({
        title: '查看评价功能开发中',
        icon: 'none'
      })
    } else {
      uni.showToast({
        title: '暂无评价信息',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('获取评价详情失败', error)
    uni.showToast({
      title: '获取评价详情失败',
      icon: 'none'
    })
  }
}

// 上传图片后的回调
const afterRead = (event) => {
  const { file } = event.detail
  ratingForm.value.images.push({
    url: file.url,
    status: 'success',
    message: '上传成功'
  })
}

// 删除图片
const deletePic = (event) => {
  const { index } = event.detail
  ratingForm.value.images.splice(index, 1)
}

// 提交评价
const submitRating = async () => {
  try {
    if (!ratingForm.value.content.trim()) {
      uni.showToast({
        title: '请输入评价内容',
        icon: 'none'
      })
      return
    }

    submitting.value = true
    
    console.log('currentOrderItem:', currentOrderItem.value)
    
    const reviewDTO = {
      fruitId: currentOrderItem.value.fruitId, // 水果ID
      fruitDetailId: currentOrderItem.value.fruitId, // 水果详情ID
      rating: ratingForm.value.score, // 评分
      content: ratingForm.value.content, // 评价内容
      images: ratingForm.value.images.map(img => img.url) // 图片列表
    }
    
    console.log('提交评价参数:', reviewDTO)
    
    const res = await reviewStore.submitReview(reviewDTO)
    
    if (res && res.code === 200) {
      uni.showToast({
        title: '评价成功',
        icon: 'success'
      })
      
      ratingForm.value = {
        score: 5,
        content: '',
        images: []
      }
      showRating.value = false
      
      // 重新加载订单列表
      let currentStatus
      switch (activeTab.value) {
        case 'all':
          currentStatus = ''
          break
        case 'unpaid':
          currentStatus = 0
          break
        case 'unshipped':
          currentStatus = 1
          break
        case 'unreceived':
          currentStatus = 2
          break
        case 'received':
          currentStatus = 3
          break
        case 'canceled':
          currentStatus = 4
          break
        case 'unrated':
          currentStatus = 5
          break
        case 'rated':
          currentStatus = 6
          break
        default:
          currentStatus = ''
      }
      loadOrders(currentStatus)
    } else {
      uni.showToast({
        title: res?.msg || '评价失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('提交评价失败', error)
    uni.showToast({
      title: '提交评价失败',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

// 跳转到售后列表
const navigateToAftersale = () => {
  uni.navigateTo({
    url: '/pages/order/aftersale'
  })
}

// 跳转到申请售后页面
const navigateToApplyAftersale = (order) => {
  uni.navigateTo({
    url: `/pages/order/apply-aftersale?orderNo=${order.orderNo}`
  })
}

// 获取订单商品总数量
const getTotalQuantity = (order) => {
  return order.orderItems.reduce((total, item) => total + item.quantity, 0)
}

// 获取订单状态对应的样式类
const getStatusClass = (status) => {
  const statusMap = {
    0: 'status-pending',    // 待付款
    1: 'status-processing', // 待发货
    2: 'status-shipping',   // 待收货
    3: 'status-success',    // 已收货
    4: 'status-cancelled',  // 已取消
    5: 'status-pending',    // 待评价
    6: 'status-success'     // 已评价
  }
  return statusMap[status] || 'status-default'
}

// 支付订单
const payOrder = async (order) => {
  try {
    if (!order || !order.orderNo) {
      uni.showToast({
        title: '订单号不存在',
        icon: 'none'
      })
      return
    }

    const res = await orderStore.payOrder(order.orderNo)
    if (res.code === 200) {
      uni.showToast({
        title: '支付成功',
        icon: 'success'
      })
      let currentStatus
      switch (activeTab.value) {
        case 'unpaid':
          currentStatus = 0
          break
        case 'unshipped':
          currentStatus = 1
          break
        case 'unreceived':
          currentStatus = 2
          break
        case 'received':
          currentStatus = 3
          break
        case 'canceled':
          currentStatus = 4
          break
        case 'unrated':
          currentStatus = 5
          break
        case 'rated':
          currentStatus = 6
          break
        default:
          currentStatus = ''
      }
      loadOrders(currentStatus)
    } else {
      uni.showToast({
        title: res.msg || '支付失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('支付订单失败', error)
    uni.showToast({
      title: '支付失败',
      icon: 'none'
    })
  }
}

// 取消订单
const cancelOrder = async (order) => {
  try {
    if (!order || !order.orderNo) {
      uni.showToast({
        title: '订单号不存在',
        icon: 'none'
      })
      return
    }

    const res = await orderStore.cancelOrder(order.orderNo)
    if (res.code === 200) {
      uni.showToast({
        title: '订单已取消',
        icon: 'success'
      })
      let currentStatus
      switch (activeTab.value) {
        case 'unpaid':
          currentStatus = 0
          break
        case 'unshipped':
          currentStatus = 1
          break
        case 'unreceived':
          currentStatus = 2
          break
        case 'received':
          currentStatus = 3
          break
        case 'canceled':
          currentStatus = 4
          break
        case 'unrated':
          currentStatus = 5
          break
        case 'rated':
          currentStatus = 6
          break
        default:
          currentStatus = ''
      }
      loadOrders(currentStatus)
    } else {
      uni.showToast({
        title: res.msg || '取消失败',
        icon: 'none'
      })
    }
  } catch (error) {
    console.error('取消订单失败', error)
    uni.showToast({
      title: '取消失败',
      icon: 'none'
    })
  }
}

// 确认收货
const confirmReceive = async (order) => {
  try {
    const res = await orderStore.confirmOrder(order.orderNo)
    if (res.code === 200) {
      uni.showToast({
        title: '确认收货成功',
        icon: 'success'
      })
      loadOrders(3)
    }
  } catch (error) {
    console.error('确认收货失败', error)
    uni.showToast({
      title: '确认失败',
      icon: 'none'
    })
  }
}

// 查看物流
const checkLogistics = (order) => {
  uni.showToast({
    title: '物流查询功能开发中',
    icon: 'none'
  })
}

// 跳转到订单详情页面
const navigateToOrderDetail = (order) => {
  uni.navigateTo({
    url: `/pages/order/order-detail?orderNo=${order.orderNo}`
  })
}
</script>

<style lang="scss" scoped>
.container {
  min-height: 100vh;
  background-color: #f8f8f8;
  padding-bottom: env(safe-area-inset-bottom);
}

.tabs-container {
  background-color: #ffffff;
  position: sticky;
  top: 0;
  z-index: 100;
  white-space: nowrap;
  border-bottom: 1rpx solid #f0f0f0;
}

.tabs {
  display: flex;
  background-color: #ffffff;
  padding: 10rpx 0;
  width: fit-content;

  .tab-item {
    display: inline-block;
    text-align: center;
    font-size: 24rpx;
    color: #666666;
    position: relative;
    padding: 16rpx 30rpx;
    flex-shrink: 0;

    &.active {
      color: #1890ff;
      font-weight: bold;

      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 40rpx;
        height: 4rpx;
        background-color: #1890ff;
        border-radius: 2rpx;
      }
    }
  }
}

.order-list {
  height: calc(100vh - 88rpx);
}

.order-item {
  margin: 20rpx;
  background-color: #ffffff;
  border-radius: 12rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
  
  &.item-hover {
    background-color: #f8f8f8;
  }

  .order-header {
    padding: 20rpx;
    border-bottom: 1rpx solid #f0f0f0;
    display: flex;
    justify-content: space-between;
    align-items: center;
    
    &.header-hover {
      background-color: #f8f8f8;
    }

    .order-no {
      font-size: 24rpx;
      color: #999999;
    }

    .order-status {
      font-size: 24rpx;
      
      &.status-pending {
        color: #1890ff;
      }
      
      &.status-processing {
        color: #40a9ff;
      }
      
      &.status-shipping {
        color: #13c2c2;
      }
      
      &.status-success {
        color: #52c41a;
      }
      
      &.status-cancelled {
        color: #999999;
      }
      
      &.status-default {
        color: #1890ff;
      }
    }
  }

  .product-item {
    display: flex;
    padding: 20rpx;
    border-bottom: 1rpx solid #f0f0f0;

    .product-image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 8rpx;
      margin-right: 20rpx;
    }

    .product-info {
      flex: 1;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .product-name {
        font-size: 28rpx;
        color: #333333;
        margin-bottom: 10rpx;
      }

      .product-price-wrap {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .product-price {
          font-size: 28rpx;
          color: #ff8800;
          font-weight: bold;
        }

        .product-quantity {
          font-size: 24rpx;
          color: #999999;
        }
      }
    }
  }

  .order-footer {
    padding: 20rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .total-wrap {
      font-size: 24rpx;
      color: #666666;

      .total-price {
        margin-left: 20rpx;
        color: #ff8800;
        font-weight: bold;
      }
    }

    .action-buttons {
      display: flex;
      gap: 20rpx;

      button {
        font-size: 24rpx;
        padding: 10rpx 30rpx;
        border-radius: 30rpx;
        background-color: #ffffff;
        border: 1rpx solid #1890ff;
        color: #1890ff;

        &.btn-primary {
          background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
          color: #ffffff;
          border: none;
        }

        &.btn-secondary {
          background-color: #ffffff;
          color: #1890ff;
        }
      }
    }
  }
}

.no-more {
  text-align: center;
  padding: 30rpx;
  font-size: 24rpx;
  color: #999999;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 200rpx;

  .empty-image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 20rpx;
  }

  text {
    font-size: 28rpx;
    color: #999999;
  }

  .btn-aftersale {
    margin-top: 20rpx;
    width: 200rpx;
    height: 60rpx;
    line-height: 60rpx;
    text-align: center;
    background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
    color: #ffffff;
    border-radius: 30rpx;
    font-size: 28rpx;
  }
}

.rating-dialog {
  background-color: #ffffff;
  border-radius: 24rpx 24rpx 0 0;
  overflow: hidden;

  .rating-header {
    padding: 30rpx;
    display: flex;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1rpx solid #f0f0f0;

    .title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333333;
    }
  }

  .rating-content {
    padding: 30rpx;

    .rate-product {
      display: flex;
      align-items: center;
      margin-bottom: 30rpx;
      
      .product-image {
        width: 100rpx;
        height: 100rpx;
        border-radius: 8rpx;
        margin-right: 20rpx;
      }
      
      .product-name {
        font-size: 28rpx;
        color: #333333;
      }
    }

    .rate-item {
      margin-bottom: 30rpx;

      text {
        display: block;
        font-size: 28rpx;
        color: #333333;
        margin-bottom: 20rpx;
      }

      .rate-textarea {
        width: 100%;
        height: 200rpx;
        padding: 20rpx;
        background-color: #f8f8f8;
        border-radius: 12rpx;
        font-size: 28rpx;
      }
    }
  }

  .rating-footer {
    padding: 30rpx;
    border-top: 1rpx solid #f0f0f0;

    .btn-submit {
      width: 100%;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      background: linear-gradient(135deg, #1890ff 0%, #40a9ff 100%);
      color: #ffffff;
      border-radius: 40rpx;
      font-size: 28rpx;
      
      &:disabled {
        opacity: 0.6;
      }
    }
  }
}

.loading-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 9999;

  .loading-spinner {
    width: 40rpx;
    height: 40rpx;
    border: 4rpx solid #f3f3f3;
    border-top: 4rpx solid #1890ff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 20rpx;
  }

  text {
    font-size: 28rpx;
    color: #666666;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>

